package com.scs.application.modules.sys.sync.impl;

import com.scs.application.core.utils.BeanUtils;
import com.scs.application.modules.sys.adapter.DictAdapter;
import com.scs.application.modules.sys.dto.DictDTO;
import com.scs.application.modules.sys.entity.DictData;
import com.scs.application.modules.sys.entity.DictType;
import com.scs.application.modules.sys.properties.SystemProperties;
import com.scs.application.modules.sys.service.DictTypeService;
import com.scs.application.modules.sys.sync.DictSyncService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:字典同步实现类
 */
@Service
public class DictSyncServiceImpl implements DictSyncService {

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private DictAdapter dictAdapter;

    /**
     * 同步字典类型数据
     */
    @Override
    public void syncDictType() {
        DictTypeService fileDictTypeService = dictAdapter.getDictTypeService(false);
        List<DictDTO> fileDictDTOs = fileDictTypeService.getDTOList();
        if (fileDictDTOs == null || fileDictDTOs.isEmpty()) {
            return;
        }

        List<DictType> needUpdateDictTypes = Lists.newArrayList();
        List<DictData> needUpdateDictDatas = Lists.newArrayList();
        List<DictType> dictTypes = dictAdapter.getDictTypeService(true).list();
        for (DictDTO dictDTO : fileDictDTOs) {
            if ("base_matr_type".equals(dictDTO.getCode())) {
                System.out.println("1111");
            }
            DictType dictType = new DictType();
            BeanUtils.copyProperties(dictDTO, dictType);
            needUpdateDictTypes.add(dictType);

            if (dictDTO.getDictDataDTOS() != null && !dictDTO.getDictDataDTOS().isEmpty()) {
                dictDTO.getDictDataDTOS().forEach(dictDataDTO -> {
                    DictData dictData = new DictData();
                    BeanUtils.copyProperties(dictDataDTO, dictData);
                    needUpdateDictDatas.add(dictData);
                });
            }
        }
        if (needUpdateDictTypes.size() > 0) {
            dictAdapter.getDictTypeService(true).saveBatch(needUpdateDictTypes);
        }
        if (needUpdateDictDatas.size() > 0) {
            dictAdapter.getDictDataService(true).saveBatch(needUpdateDictDatas);
        }
    }
}
